<?php
/** * Signup Class *
 * @package TIAP 
 * @subpackage Controller 
 * @category user 
 * @author Ibnu Triyono 
 * @description Handling Signup, activation, and anything related to login info, except login itsef
 * @link http://twitter.com/ibnutri 
 */
class Signup extends Controller {
    function Signup() {
        parent::Controller();
        //$this->output->enable_profiler(TRUE);
        $this->load->helper('form');
        $this->load->model('User_model');
        $this->load->model('Network_model');
        $this->load->model('User_network_model');
        $this->load->library('recaptcha');
        $this->load->library('form_validation');
        $this->load->helper('form');
        $this->lang->load('recaptcha');
        if (!$this->User_model->check_login()) {
        } else {
            redirect('profile');
            exit;
        }
    }
    function index() {
	$this->load->library('facebook_connect');
	$this->load->config('facebook');
	$_api_key = $this->config->item('facebook_api_key');
	$oauth_token = $_COOKIE['fbs_'.$_api_key];
	if(!empty($oauth_token)){
	    redirect('signup/facebook_connect');
	}
	//$this->facebook_connect->client->users_getLoggedInUser($one_line_story_templates, $short_story_templates, $full_story_template);
        $data = "";
        $data = array('username' => '', 'firstname' => '', 'surname' => '', 'email' =>
            '', 're_email' => '', );
        $submit_button = $this->input->post('submit');
        if ($submit_button !== "") { // if submit button pressed
            $this->form_validation->set_rules('recaptcha_response_field', 'Captcha field', 'callback_check_captcha');
            $this->form_validation->set_rules('username', 'Username',
                'required|min_length[6]|callback_check_username');
            $this->form_validation->set_rules('firstname', 'First name', 'required');
            $this->form_validation->set_rules('surname', 'Surname', 'required');
            $this->form_validation->set_rules('email', 'e-mail',
                'required|valid_email|callback_check_email');
            $this->form_validation->set_rules('re_email', 're-typed e-mail',
                'required|valid_email|matches[email]');
            $this->form_validation->set_rules('password', 'Password',
                'required|min_length[6]');
            $this->form_validation->set_rules('re_password', 're-typed Password',
                'required|min_length[6]|matches[password]');
            // data retrieving
            $username = trim($this->input->post('username'));
            $firstname = trim($this->input->post('firstname'));
            $surname = trim($this->input->post('surname'));
            $email = trim($this->input->post('email'));
            $re_email = $this->input->post('re_email');
            $password = $this->input->post('password');
            if ($this->form_validation->run() == true) {
                $succes_id = $this->User_model->signup_user($username, $firstname, $surname, $email,
                    $password);
                if ($succes_id != false) {
                    redirect('signup/success/' . $succes_id);
                }
            } else {
            }
            $data = array('username' => $username, 'firstname' => $firstname, 'surname' => $surname,
                'email' => $email, 're_email' => $re_email, );
            // give retrieved data to model
        } // end if submit button pressed
        $data['recaptcha']=$this->recaptcha->get_html();
	//breadcrum config
	$breadcrumb_list = array(
		array('name'=>'Sign up', 'href'=>site_url('static_page/signup')),
		);
	$data['breadcrumb_list'] = $breadcrumb_list;
	
        $this->load->view(TEMPLATE_NAME . '/front/signup/signup_form', $data);
    }
    function facebook_connect(){
	$this->load->library('facebook_connect');
	$this->load->config('facebook');
	$_api_key = $this->config->item('facebook_api_key');
	
	$oauth_token = $_COOKIE['fbs_'.$_api_key];
	$oauth_token = str_replace('"',"",$oauth_token);
	$oauth_url = 'https://graph.facebook.com/me?' .$oauth_token;
	$user_facebook = get_web_page($oauth_url);	
	if(!empty($user_facebook)){
	    $user_facebook = json_decode($user_facebook['content'],TRUE);
	}
	$oauth_token = ""; // save token yang disini salah, bukan yang ini maksudnya
	if(!empty($user_facebook)){
	    if($this->User_model->check_facebook_user($user_facebook['id'])){
	      //$fetched_info = array('name','first_name','last_name','email');
	      //$user_info = $this->facebook_connect->client->users_getInfo($this->facebook_connect->user_id,$fetched_info);
	      $user_email = $user_facebook['email'];
	      $user_first_name = $user_facebook['first_name'];
	      $user_last_name = $user_facebook['last_name'];
	      $user_name = $user_facebook['name'];
	      $user_facebook_id=$user_facebook['id'];
	      $submit_button = $this->input->post('submit');
	      $user_name = str_replace(" ","_",$user_name);
	      $data = array(
		'username'=>$user_name,
		'email'=>$user_email,
	      );
	      if($submit_button != ""){
		$this->form_validation->set_rules('username', 'Username',
                'required|min_length[6]|callback_check_username');
		$this->form_validation->set_rules('email', 'e-mail',
                'required|valid_email|callback_check_email');
                $this->form_validation->set_rules('password', 'Password',
                'required|min_length[6]');
	        $this->form_validation->set_rules('re_password', 're-typed Password',
                'required|min_length[6]|matches[password]');


		if ($this->form_validation->run() == true) {
		  $user_name = $this->input->post('username',true);
		  $user_email = $this->input->post('email',true);
		  $user_password = $this->input->post('password',true);
		  $data = array(
		  'username'=>$user_name,
		  'email'=>$user_email,
		);
		  $this->User_model->signup_user_facebook($user_name, $user_first_name, $user_last_name, $user_email,$user_password,$user_facebook_id,$oauth_token,TRUE);
                  $this->User_model->update_avatar_facebook($user_facebook['id']);
		  $this->User_model->force_login_facebook($user_facebook['id']);
		  redirect('profile');
		}
	      }
	      $this->load->view(TEMPLATE_NAME.'/front/signup/facebook_connect',$data);
	    }else{
	      $this->User_model->force_login_facebook($user_facebook['id']);
	      redirect('profile');
	    }
	}else{
	      redirect('login');
	}
	
    }
    function facebook_test(){
	$this->load->library('facebook_connect');

	if(!empty($this->facebook_connect->user_id)){
	      $user_facebook=$this->facebook_connect->user;
	      $user_info = $this->facebook_connect->client->users_getInfo($user_facebook['uid'],'email');
	      $user_email = $user_info[0]['email'];
	      echo $user_email;
	}
	
    }
    function success() {
        $data = array('email' => '');
        $signup_success_code = $this->uri->segment(3);
        $signup_success_code = $this->input->xss_clean($signup_success_code);
        $data['success_string'] = $signup_success_code;
        if ($signup_success_code !== "") {
            if ($user_detail = $this->User_model->get_user_by_success_code($signup_success_code)) {
		    // script di bawah di komen karena nggak ada network south africa,
		    // dulunya ada, sekarang nggak ada
		    
		$main_network_detail = $this->Network_model->get_main_network(); 
		if(!$this->User_network_model->check_network_member($user_detail['id'],$main_network_detail['id'])){
		    
		  $this->User_network_model->join_network($main_network_detail['id'],$user_detail['id'],TRUE);
		}
		     
                $data['user_detail'] = $user_detail;
	//breadcrum config
	$breadcrumb_list = array(
		array('name'=>'Sign up', 'href'=>site_url('static_page/signup')),
		);
	$data['breadcrumb_list'] = $breadcrumb_list;

                $this->load->view(TEMPLATE_NAME . '/front/signup/signup_success', $data);
            } else {
                redirect('signup');
            }
        } else {
            redirect('signup');
        }
    }
    function check_captcha($val) {
      $result = $this->recaptcha->check_answer($_SERVER["REMOTE_ADDR"],$this->input->post('recaptcha_challenge_field'),$val);
      if ($result) {
	return true;
      } else {
	$this->form_validation->set_message('check_captcha','Incorrect Security Image Response');
	return false;
      }
    } 
    function check_username($val) {
        if (!$this->User_model->check_available_username($val)) {
            $this->form_validation->set_message('check_username', '%s ' . $val .
                ' is already on our system, please use another %s');
            return false;
        } else {
            return true;
        }
    }
    function check_email($val) {
        if (!$this->User_model->check_available_email($val)) {
            $this->form_validation->set_message('check_email', '%s ' . $val .
                ' is already on our system, please use another %s');
            return false;
        } else {
            return true;
        }
    }
    /*
    * method check_forgot
    * @description required for 
    * @parameter $val string username or email
    * @return TRUE if  user exist, otherwise false
    */
    function check_forgot($val) {
        if ($this->User_model->find_user($val)) {
            return true;
        } else {
            $this->form_validation->set_message('check_forgot', 'oh snap! we couldn\'t find you!');
            return false;
        }
    }
    function success_resend() {
        $signup_success_code = $this->uri->segment(3);
        $signup_success_code = $this->input->xss_clean($signup_success_code);
        $data['success_string'] = $signup_success_code;
        $submit = $this->input->post('submit');
        if ($submit !== "") {
            if ($signup_success_code !== "") {
                if ($user_detail = $this->User_model->get_user_by_success_code($signup_success_code)) {
                    $this->User_model->resend_activation_email($signup_success_code);
                    redirect('signup/success/' . $signup_success_code);
                } else {
                    redirect('signup');
                }
            } else {
                redirect('signup');
            }
        }
        redirect('signup/success/' . $signup_success_code);
    }
    function success_update_email() {
        $data = array('email' => '');
        $signup_success_code = $this->uri->segment(3);
        $signup_success_code = $this->input->xss_clean($signup_success_code);
        $data['success_string'] = $signup_success_code;
        $this->form_validation->set_rules('email', 'e-mail',
            'required|valid_email|callback_check_email');
        if ($signup_success_code !== "") {
            if ($user_detail = $this->User_model->get_user_by_success_code($signup_success_code)) {
                if ($this->form_validation->run() == true) {
                    $email = $this->input->post('email');
                    $this->User_model->update_email_on_success_page($email, $signup_success_code);
                }
                redirect('signup/success/' . $signup_success_code);
            } else {
                redirect('signup');
            }
        } else {
            redirect('signup');
        }
    }
    /*
    * method activate
    * activate user by link given in signup notify email and auto loggin for user
    * 
    */
    function activate() {
        $username = $this->uri->segment(3);
        $activation_code = $this->uri->segment(4);
        $username = $this->input->xss_clean($username);
        $activation_code = $this->input->xss_clean($activation_code);

    	//breadcrum config
    	$breadcrumb_list = array(
		  array('name'=>'Sign up', 'href'=>site_url('static_page/signup')),
		);
        
	    $data['breadcrumb_list'] = $breadcrumb_list;
        $userNameAlt = str_replace('_','.',$username);
        //echo $username.' '.$activation_code;
        if ($username = $this->User_model->activate($username, $activation_code)) {
            if (!$this->User_model->force_login($username)) {
                redirect('signup');
                exit;
            }
            $this->load->view(TEMPLATE_NAME . '/front/signup/signup_active');
        }else {
            $this->load->view(TEMPLATE_NAME . '/front/signup/signup_active_fail');
        }
    }
    /*
    * method forgot_password
    * forgot password form, to retrieve email , to get link to reset password
    * 
    */
    function forgot_password() {

	//breadcrum config
	$breadcrumb_list = array(
		array('name'=>'Forgot password', 'href'=>site_url('static_page/forgot_password')),
		);
	$data['breadcrumb_list'] = $breadcrumb_list;
        if ($this->input->post('submit') != '') {
            $this->form_validation->set_rules('username', 'Username',
                'required|min_length[6]|callback_check_forgot');
            if ($this->form_validation->run()) {
                $username = $this->input->post('username', true);
                if ($user_forgoted = $this->User_model->find_user($username)) {
		    if($user_forgoted['activation_status'] == 'active'){
			$reset_password_code = $this->User_model->create_reset_password_code($user_forgoted['email'],
			    $user_forgoted['username']);
			$this->User_model->set_reset_password_code($user_forgoted['id'], $reset_password_code);
			$this->User_model->send_forgot_password_email($user_forgoted['email'], $user_forgoted['username'],
			    $reset_password_code);
                        $data['email'] = $user_forgoted['email'];
			$this->load->view(TEMPLATE_NAME . '/front/signup/forgot_password_success',$data);
		    }else{ 
                        $data['user_detail'] = $user_forgoted;
                        $this->User_model->resend_activation_email($user_forgoted['success_page_code'],substr_replace($user_forgoted['real_pass'],'***',0,3));
			$this->load->view(TEMPLATE_NAME . '/front/signup/forgot_password_inactive',$data);
		    }
                } else {
                    $this->load->view(TEMPLATE_NAME . '/front/signup/forgot_password');
                }
            } else {
                $this->load->view(TEMPLATE_NAME . '/front/signup/forgot_password');
            }
        } else {
            $this->load->view(TEMPLATE_NAME . '/front/signup/forgot_password');
        }
    }
    /*
    * method reset_password
    * reset password form, to retrieve email , to get link to reset password
    * 
    */
    function reset_password() {
        $username = $this->uri->segment(3);
        $reset_password_code = $this->uri->segment(4);
        if ($username != '' && $reset_password_code != '') {
            $codes = explode('-', $reset_password_code);
            if ($this->User_model->check_reset_code($username, $codes)) {
                $data = array('username' => $username, 'reset_password_code' => $reset_password_code);
                if ($this->input->post('submit', true) != '') {
                    $this->form_validation->set_rules('password', 'Password',
                        'required|min_length[6]');
                    $this->form_validation->set_rules('retype_password', 're-typed Password',
                        'required|min_length[6]|matches[password]');
                    if ($this->form_validation->run()) {
                        $this->User_model->reset_password($username, $this->input->post('password', true));
                        redirect('signup/reset_password_success');
                    }
                }
	//breadcrum config
	$breadcrumb_list = array(
		array('name'=>'Sign up', 'href'=>site_url('static_page/signup')),
		);
	$data['breadcrumb_list'] = $breadcrumb_list;

                $this->load->view(TEMPLATE_NAME . '/front/signup/reset_password', $data);
            } else {
                redirect('signup/forgot_password');
            }
        } else {
            redirect('signup/forgot_password');
        }
    }
    /*
    * method reset_password_success 
    * method to test the forgot password template
    */
    function reset_password_success() {
        $this->load->view(TEMPLATE_NAME . '/front/signup/reset_password_success');
    }
    /*
    * method forgot_password_template 
    * method to test the forgot password template
    */
    function forgot_password_template() {
        $data = array('username' => 'ibnutri', 'activation_link' =>
            'twitter.com/ibnutri');
        $this->load->view(TEMPLATE_NAME . '/front/mail/forgot_password_request', $data);
    }
    /**
     * method check_email_json
     * for validation with jquery to check available email in table user_tiab
     * 
     * @return string result
     */
    function check_email_json() {
        $email = $this->input->post('email');
        if (!$this->User_model->check_available_email($email)) {
            $result_email = 'FALSE';
        } else {
            $result_email = 'TRUE';
        }
        echo json_encode($result_email);
    }

    function check_email_json_remote() {
        $email = $this->input->post('email');
        if (!$this->User_model->check_available_email($email)) {
            $result_email = false;
        } else {
            $result_email = true;
        }
        /*ob_start();
        echo 'email : '.$email.' -- '.$result_email;
        echo '-------------------\n';
        print_r($_POST);
        echo '-------------------\n';
        print_r($_GET);
        echo '-------------------\n';
        print_r($_SERVER);
        echo '-------------------\n';
        $resultData = ob_get_contents();
        ob_end_clean();
        $fp = fopen('debug.txt', 'a+');
        fwrite($fp, $resultData);
        fclose($fp);*/
        echo json_encode($result_email);
    }

    function check_username_json() {
        $username = $this->input->post('username');
        if (!$this->User_model->check_available_username($username)) {
            $result_username = 'FALSE';
        } else {
            $result_username = 'TRUE';
        }
        echo json_encode($result_username);
    }

    function check_username_json_remote() {
        $username = $this->input->post('username');
        if (!$this->User_model->check_available_username($username)) {
            $result_username = false;
        } else {
            $result_username = true;
        }
        echo json_encode($result_username);
    }
}
/* End of file signup.php */
/* Location: ./system/application/controllers/signup.php */
?>